import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-01-17
 * Time: 10:39
 */

/**
 * 快乐数
 * 快慢双指针才是好的解法
 */

class Solution1_1 {
    public boolean isHappy(int n) {
        Map<Integer,Integer> map = new HashMap<>();
        boolean sign = true;
        int result = n;
        while(sign){
            while(true){
                result = calculate(result);
                if(result == 1) return true;
                if(!map.containsKey(result)){
                    map.put(result,0);
                }else{
                    break;
                }
            }
            sign = false;
        }
        return false;
    }

    // 封装一个方法计算这个数的各个位的平方和，每次模10
    public int calculate(int n) {
        int ret = 0;
        while (n != 0) {
            int tem = n % 10;
            ret += Math.pow(tem, 2);
            n = n / 10;
        }
        return ret;
    }
}
class Solution1{
    public static int sumResult(int n ){
        int sum = 0;
        while( n != 0){
            sum += Math.pow(n%10 , 2);
            n = n/10;
        }
        return sum;
    }
    public boolean isHappy(int n){
        int slow = n , fast = sumResult(n);
        while(slow != fast){
            slow = sumResult(slow);
            fast = sumResult(sumResult(fast));
        }
        return slow == 1;
    }
}
public class Test1 {
    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        solution1.isHappy(19);
    }
}
